<?php

namespace App\Services\Repo;


use App\Models\SimCard;
use App\Services\Excel\ExcelReader;
use App\Services\Excel\ImportError;
use App\Services\Interfaces\RepoServiceInterface;
use Illuminate\Database\Eloquent\Model;
use DB;
use Helper;
use Illuminate\Database\Eloquent\Collection;

class SimCardRepo implements RepoServiceInterface
{
    public function create(array $_options = null):Model
    {
        $sim_card = new SimCard();
        return $sim_card;
    }

    public function createMany(array $_options):int
    {
        //TODO:aggregate,创建卡柜太多需分批处理
        $sim_cards = new Collection();
        $start_num = $_options['startNum'];
        $books = $_options['books'];
        $pages = $_options['pages'];
        $boxes = $_options['boxes'];
        $checkIndex = [];
        for ($book = 0; $book < $books; $book++) {
            for ($page = 1; $page <= $pages; $page++) {
                for ($box = 1; $box <= $boxes; $box++) {
                    $sim_card = new SimCard();
                    $sim_card->mobile = '';
                    $index['book'] = $book + $start_num;
                    $index['page'] = $page;
                    $index['box'] = $box;
                    $sim_card->index = $index;
                    $sim_card->indexCache = $sim_card->convertIndex();
                    $sim_card->company_id = '';
                    $sim_cards->push($sim_card);
                    array_push($checkIndex, $sim_card->indexCache);
                }
            }
        }
        //去除已添加卡柜
        $exist_cards = SimCard::whereIn('indexCache', $checkIndex)
            ->get(['indexCache'])
            ->pluck('indexCache')
            ->all();
        $sim_cards = $sim_cards->filter(function($sim_card) use ($exist_cards){
            return !in_array($sim_card->convertIndex(), $exist_cards);
        });

        if (count($sim_cards)) {
            $sim_cards = $sim_cards->toArray();
            $sim_cards = array_map(function($sim_card){
                $temp['mobile'] = $sim_card['mobile'];
                $temp['index'] = $sim_card['index'];
                $temp['company_id'] = $sim_card['company_id'];
                $temp['indexCache'] = $sim_card['indexCache'];
                return $temp;
            },$sim_cards);
            return DB::table('sim_cards')->insert(array_values($sim_cards));
        }
        return count($sim_cards);
    }

    public function read($limit = 0)
    {
        $data = Helper::get_filter();
        $sort = Helper::get_filter('s');
        $order = 'asc';
        $key = 'indexCache';
        if ($sort) {
            $key = array_keys($sort)[0];
            if ($sort[$key] === -1) {
                $order = 'desc';
            }
        }
        return SimCard::search($data)
            ->orderBy($key, $order)
            ->paginate(20);
    }

    public function find(array $_filter):Model
    {
        $sim_card = new SimCard();
        return $sim_card;
    }

    public function update(array $_filter, array $_update_data):bool
    {
        $sim_card = SimCard::find($_filter)->first();
        if (!is_null($sim_card)) {
            $sim_card->mobile = $_update_data['mobile'];
            return $sim_card->save();
        } else {
            return false;
        }
    }

    public function delete(array $_filter):bool
    {
        // TODO: Implement delete() method.
    }

    /**
     * 手机号导入操作
     * @param $file_url
     * @return array
     */
    public function importMobile($file_url) {
        //获取表格内数据
        $excel_reader = new ExcelReader($file_url);
        if (!in_array('手机号', $excel_reader->table_title)
            || !in_array('卡位', $excel_reader->table_title)) {
            return ['手机号、卡位列名缺失'];
        }
        $excel_content = $excel_reader->readFile();
        //导入错误信息类
        $error = new ImportError();
        foreach ($excel_content as $row) {
            $mobile = preg_match('/^1[3-8]\d{9}$/', $row['手机号'])
                ? $row['手机号'] : '';
            $card_index = (int) $row['卡位'];
            //数据有效性验证
            if (!$mobile && !$card_index) {
                continue;
            }
            if (!$mobile || !$card_index) {
                $error->addErrorIndex($error::MISSING_INFO,
                    $row['index']);
                continue;
            }
            $simCard = SimCard::where([
                '$or' => [
                    ['mobile' => $mobile],
                    ['indexCache' => $card_index]
                ]
            ])->get();
            //数据是否可写入验证
            switch ($simCard->count()) {
                case 0:
                    $error->addErrorIndex($error::SIMCARD_NOT_EXIST,
                        $row['index']);
                    break;
                case 1:
                    if ($simCard->get(0)->mobile) {
                        $error->addErrorIndex($error::SIMCARD_HAS_MOBILE,
                            $row['index']);
                    } else {
                        SimCard::find($simCard->get(0)->_id)
                            ->update(['mobile' => $mobile]);
                    }
                    break;
                default:
                    $error->addErrorIndex($error::MOBILE_EXIST,
                        $row['index']);
            }
        }
        //错误信息格式化
        return $error->getMessage();
    }
}